package com.springboot.ww.platform.pd.lms.demo;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpRequest;
import com.springboot.ww.platform.pd.dto.AuthParamValueVO;
import com.springboot.ww.platform.pd.dto.PdStoreTokenVO;
import com.springboot.ww.platform.pd.http.PdHttpProxy;
import com.springboot.ww.platform.pd.http.ResponseMsg;
import com.springboot.ww.platform.pd.lms.api.PdSkuPriceResp;
import com.springboot.ww.platform.pd.lms.api.PdStockEditReq;
import com.springboot.ww.platform.pd.lms.constant.PdApiConstants;
import com.springboot.ww.platform.pd.lms.service.impl.PdProxyImpl;
import com.springboot.ww.platform.pd.util.SignUtil;
import com.ww.springboot.boot.utils.Func;
import com.ww.springboot.boot.utils.json.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;

import java.util.*;

import static cn.hutool.core.util.ClassUtil.isSimpleValueType;

/**
 * 描述：
 *
 * @author 🧑 ‍wanwei
 * @since 2024-05-23 16:01
 */
@Slf4j
public class PdddTest {

    private static final String US_URL = "https://openapi-b-us.temu.com/openapi/router";
    private static final String CN_URL = "https://openapi.kuajingmaihuo.com/openapi/router";


    public static void main(String[] args) {
        String ss = " {\n" +
                "            \"authId\": \"1825475827131170817\",\n" +
                "            \"platformCode\": \"PD\",\n" +
                "            \"siteCode\": null,\n" +
                "            \"name\": \"HouseWonders\",\n" +
                "            \"code\": \"pinduoduo_0JY2\",\n" +
                "            \"storeStatus\": 1,\n" +
                "            \"token\": \"upsfaq4e11erdw4nfnjdnnivbmc89zmi92mdmztvslbxzgu41b50ztthdqr\",\n" +
                "            \"paramMap\": {\n" +
                "                \"doMain\": \"openapi-b-global.temu.com\",\n" +
                "                \"appKeyCn\": \"385a404391e656960ac90d061ef7e187\",\n" +
                "                \"tokenCn\": \"rwb8h4baqfkfdj3dohy1gcnxgmopob5z0b1keivg6xckr8lwdkosbr8b\",\n" +
                "                \"tokenGlobal\": \"\",\n" +
                "                \"currency\": \"\",\n" +
                "                \"appSecretCn\": \"49855e1f296703d149b26ab2167a10c73da48323\",\n" +
                "                \"appSecret\": \"fab59e973b946c2172e62c7c3ca0896d07e5e029\",\n" +
                "                \"appKey\": \"04bc9771b64cbd933c1dc355243435aa\"\n" +
                "            },\n" +
                "            \"apiUrl\": \"4.242.79.188\"\n" +
                "        }";
        AuthParamValueVO authParamValueVO = JsonUtil.parse(ss, AuthParamValueVO.class);
        PdStoreTokenVO storeVO = PdStoreTokenVO.builder().apply(authParamValueVO);


//        PddImageDTO pddImageDTO = new PdProxyImpl().uploadImage(storeVO, "https://image.izehui.com/PIC_1000/ZP/ZP0220/ZP0220QL.jpg");
//        System.out.println(JsonUtil.toJson(pddImageDTO));


        List<PdSkuPriceResp.ProductSkuSupplierPriceListDTO> skuPriceList = new PdProxyImpl().getSkuPriceList(storeVO,
                Arrays.asList("73273829909"));

        System.out.println(JsonUtil.toJson(skuPriceList));


        //goodPrice(storeVO);
        //good(storeVO);
        //stock(storeVO);
//        stockEdit(storeVO);
//        stock(storeVO);
        //WH-04883221708951571
        //warehouse(storeVO);
        //goodUS(storeVO);
//        goodSku(storeVO);
//        price(storeVO);


//        List<PdSkuPriceResp.ProductSkuSupplierPriceListDTO> skuPriceList = new PdProxyImpl().getSkuPriceList(storeVO, Arrays.asList("8844072594"));
//        System.out.println(JsonUtil.toJson(skuPriceList));

//        List<PdBrandResp.ResultDTO.PageItemsDTO> brand = new PdProxyImpl().getBrand(storeVO);
//        System.out.println(JsonUtil.toJson(brand));

    }

    private static void goodPrice(PdStoreTokenVO storeVO) {
        Map<String, Object> map = new TreeMap<>();
        map.put("productSkuIds", Arrays.asList(7629749265L));
        cnToken(map, storeVO, "bg.goods.price.list.get");
        String s = JsonUtil.toJson(map);
        System.out.println(s);
        String body = HttpRequest.post(CN_URL).body(s).execute().body();
        System.out.println(body);
    }

    private static void goodUS(PdStoreTokenVO storeVO) {
        Map<String, Object> map = new TreeMap<>();
        map.put("data_type", "JSON");
        map.put("pageSize", 20);
        map.put("page", 0);
        map.put("skuSearchType", 2);
        usToken(map, storeVO, PdApiConstants.GET_GOOD_LIST_US);
        String resultResp = postUS(storeVO.getApiUrl(), JsonUtil.toJson(map));
        System.out.println(resultResp);
    }

    private static void getCarrierId(PdStoreTokenVO storeVO) {
        Map<String, Object> map = new TreeMap<>();
        map.put("regionId", "211");
        usToken(map, storeVO, PdApiConstants.GET_CARRIER_LIST);
        String resultResp = postUS(storeVO.getApiUrl(), JsonUtil.toJson(map));
        System.out.println(resultResp);
    }

    private static void price(PdStoreTokenVO storeVO) {
        Map<String, Object> map = new TreeMap<>();
        map.put("pageSize", 20);
        map.put("page", 0);
        //map.put("skuSearchType", 1);
        map.put("goodsSearchType", 1);
        map.put("searchText", "603080699522795");
        //usToken(map, storeVO, PdApiConstants.GET_GOOD_LIST_US);
        usToken(map, storeVO, "bg.local.goods.list.query");
        String resultResp = postUS("", JsonUtil.toJson(map));
        System.out.println(resultResp);
    }

    /**
     * 如果能查到标发货信息 就走修改接口
     */
    private static void shipmentGet(PdStoreTokenVO storeVO) {
        Map<String, Object> map = new TreeMap<>();
        map.put("parentOrderSn", "PO-211-06682318957430379");
        map.put("orderSn", "211-06682339928950379");
        usToken(map, storeVO, PdApiConstants.SHIPMENT_GET);
        String resultResp = postUS("", JsonUtil.toJson(map));
        System.out.println(resultResp);
    }

    private static void detail(PdStoreTokenVO storeVO) {
        Map<String, Object> map = new TreeMap<>();
        map.put("parentOrderSn", "PO-211-00998419950713537");

        usToken(map, storeVO, "bg.order.detail.get");
        String resultResp = postUS("", JsonUtil.toJson(map));
        System.out.println(resultResp);
    }

    private static void getLabel(String url, PdStoreTokenVO storeVO) {
        System.out.println(url);
        HttpGet httpGet = new HttpGet(url);
        Map<String, Object> treeMap = new TreeMap<>();
        treeMap.put("toa-app-key", storeVO.getAppKey());
        treeMap.put("toa-access-token", storeVO.getToken());
        treeMap.put("toa-random", Func.md5Hex(UUID.randomUUID().toString()));
        Long time = System.currentTimeMillis() / 1000;
        treeMap.put("toa-timestamp", time);
        // 生成要签名的字符串
        StringBuilder signText = new StringBuilder();
        treeMap.entrySet().forEach(entry -> {
            if (isSimpleValueType(entry.getValue().getClass())) {
                signText.append(entry.getKey()).append(entry.getValue());
            } else {
                signText.append(entry.getKey()).append(JsonUtil.toJson(entry.getValue()));
            }
        });
        String s = storeVO.getAppSecret() + signText + storeVO.getAppSecret();
        for (Map.Entry<String, Object> entry : treeMap.entrySet()) {
            httpGet.setHeader(entry.getKey(), String.valueOf(entry.getValue()));
        }
        httpGet.setHeader("toa-sign", Func.md5Hex(s).toUpperCase());
        //System.out.println(httpGet.getAllHeaders());
        cn.hutool.core.io.FileUtil.writeBytes(PdHttpProxy.proxyByteWithRequest("4.242.79.188", httpGet), "C:\\Users\\ZH500\\桌面\\test\\" + System.currentTimeMillis() + ".png");
    }

    private static void getForecast(PdStoreTokenVO storeVO) {
        Map<String, Object> map = new TreeMap<>();
        map.put("packageSnList", Arrays.asList("PK-5226980767171271382"));

        usToken(map, storeVO, "bg.logistics.shipment.result.get");
        String resultResp = postUS("", JsonUtil.toJson(map));
        System.out.println(resultResp);
    }

    private static void usToken(Map<String, Object> map, PdStoreTokenVO storeVO, String api) {
        map.put("data_type", "JSON");
        map.put("access_token", storeVO.getToken());
        String sign = SignUtil.pd(map, storeVO.getAppKey(), storeVO.getAppSecret(), api);
        map.put("sign", sign);
    }


    private static String postUS(String proxyHost, String body) {
        proxyHost = getRealApiUrl(proxyHost);
        HttpPost httpPost = new HttpPost(US_URL);
        StringEntity reqEntity = new StringEntity(body, "UTF-8");
        reqEntity.setContentEncoding("UTF-8");
        reqEntity.setContentType("application/json");
        httpPost.setEntity(reqEntity);
        try {
            ResponseMsg responseMsg = PdHttpProxy.proxyWithRequest(proxyHost, httpPost);
            log.info("拼多多请求：" + body + " | " + JsonUtil.toJson(responseMsg));
            if (responseMsg.getStatus() != 200 || ObjectUtil.isEmpty(responseMsg.getResult())) {
                throw new RuntimeException("拼多多接口调用失败：" + JsonUtil.toJson(responseMsg));
            }
            return responseMsg.getResult();
        } catch (Exception e) {
            log.info("拼多多请求异常：" + body + " | " + e.getMessage());
            throw e;
        }
    }

    private static String getRealApiUrl(String apiUrl) {
        if (ObjectUtil.isEmpty(apiUrl)) {
            return "4.242.79.188";
        }
        int index = apiUrl.lastIndexOf("//");
        if (index < 0) {
            index = 0;
        } else {
            index += 2;
        }
        apiUrl = apiUrl.substring(index);
        return apiUrl;
    }

    private static void good(PdStoreTokenVO storeVO) {
        int page = 1;

        Map<String, Object> map = new TreeMap<>();
        map.put("pageSize", 100);
        map.put("page", page);
        //map.put("goodsSearchType", 1);
//        map.put("createdAtStart", DateUtil.addDate(new Date(),-10).getTime());
//        map.put("createdAtEnd", System.currentTimeMillis());
        //String sign = SignUtil.pd(map, "d0d421fc3ba30209b15f92c8f0eb5c2e", "656cee40abd7b3122f4159b88ecd5c1744502844", PdApiConstants.GET_GOOD_LIST);
        //String sign = SignUtil.pd(map, "d0d421fc3ba30209b15f92c8f0eb5c2e", "656cee40abd7b3122f4159b88ecd5c1744502844", "");
        //usToken(map,storeVO,PdApiConstants.GET_GOOD_LIST);
        cnToken(map, storeVO, PdApiConstants.GET_GOOD_LIST);
        String body = HttpRequest.post(CN_URL).body(JsonUtil.toJson(map)).execute().body();
        page++;
        System.out.println(body);


    }

    private static void goodSku(PdStoreTokenVO storeVO) {
        int page = 0;
        Map<String, Object> map = new TreeMap<>();
        map.put("pageSize", 100);
        map.put("page", page);
        map.put("skuSearchType", 2);
        map.put("searchText", "602629191112478");
//        map.put("createdAtStart", DateUtil.addDate(new Date(),-10).getTime());
//        map.put("createdAtEnd", System.currentTimeMillis());
        //usToken(map, storeVO, PdApiConstants.GET_GOOD_LIST);
        usToken(map, storeVO, "bg.local.goods.sku.list.query");
        String resultResp = postUS("", JsonUtil.toJson(map));
        System.out.println(resultResp);
    }

    private static void warehouse(PdStoreTokenVO storeVO) {
        Map<String, Object> map = new TreeMap<>();
        usToken(map, storeVO, "bg.logistics.warehouse.list.get");
        String resultResp = postUS("", JsonUtil.toJson(map));
        System.out.println(resultResp);
    }

    private static void optimize(PdStoreTokenVO storeVO) {
        Map<String, Object> map = new TreeMap<>();
        map.put("warehouseId", "WH-10037186068632929");
        map.put("orderSnList", Arrays.asList("211-00998488108153537"));
        map.put("weight", "0.1712");
        map.put("weightUnit", "lb");
        map.put("length", "55.115");
        map.put("width", "8.2677");
        map.put("height", "0.7874");
        map.put("dimensionUnit", "in");
        usToken(map, storeVO, "bg.logistics.shippingservices.get");
        String resultResp = postUS("", JsonUtil.toJson(map));
        System.out.println(resultResp);

    }

    private static void getSignCompany(PdStoreTokenVO storeVO) {
        Map<String, Object> map = new TreeMap<>();
        map.put("regionId", "211");
        usToken(map, storeVO, "bg.logistics.companies.get");
        System.out.println(postUS("", JsonUtil.toJson(map)));
    }

    private static void orderList(PdStoreTokenVO storeVO) {
        Map<String, Object> map = new TreeMap<>();
        map.put("pageNumber", "1");
        map.put("pageSize", "100");
//        map.put("updateAtStart", DateUtil.addDay(new Date(), -4).getTime() / 1000);
//        map.put("updateAtEnd", DateUtil.addDay(new Date(), -3).getTime() / 1000);
        map.put("data_type", "JSON");
        map.put("parentOrderSnList", JsonUtil.toJson(Arrays.asList("PO-211-01291394939511279")));//最多20个
        usToken(map, storeVO, "bg.order.list.get");
        System.out.println(postUS("", JsonUtil.toJson(map)));
    }

    private static void receiver(PdStoreTokenVO storeVO) {
        Map<String, Object> map = new TreeMap<>();
        map.put("parentOrderSn", "PO-211-20162783155833997");
        usToken(map, storeVO, PdApiConstants.GET_ORDER_RECEIVER);
        System.out.println(postUS("", JsonUtil.toJson(map)));
    }


    private static void stock(PdStoreTokenVO storeVO) {
        Map<String, Object> map = new TreeMap<>();
        map.put("productSkcId", "1876471597");
        cnToken(map, storeVO, PdApiConstants.GET_STOCK_HALF);
        String s = JsonUtil.toJson(map);
        System.out.println(s);
        String body = HttpRequest.post("https://openapi.kuajingmaihuo.com/openapi/router").body(s).execute().body();
        System.out.println(body);


    }

    private static void stockEdit(PdStoreTokenVO storeVO) {
        Map<String, Object> map = new TreeMap<>();
        map.put("productSkcId", "1710010984");
        map.put("quantityChangeMode", "2");
        List<PdStockEditReq> pdStockEditReqs = new ArrayList<>();
        pdStockEditReqs.add(PdStockEditReq.builder()
                .targetStockAvailable(50)
                .productSkuId("3687421846")
                .warehouseId("WH-09478850478233991")
                .build());
        map.put("skuStockChangeList", JsonUtil.toJson(pdStockEditReqs));
        cnToken(map, storeVO, PdApiConstants.STOCK_EDIT_HALF);
        String s = JsonUtil.toJson(map);
        System.out.println(s);
        String body = HttpRequest.post("https://openapi.kuajingmaihuo.com/openapi/router").body(s).execute().body();
        System.out.println(body);


    }

    private static void cnToken(Map<String, Object> map, PdStoreTokenVO storeVO, String api) {
        map.put("data_type", "JSON");
        map.put("access_token", storeVO.getTokenCn());
        String sign = SignUtil.pd(map, storeVO.getAppKeyCn(), storeVO.getAppSecretCn(), api);
        map.put("sign", sign);
    }
}
